import co from 'co';

import { model as DeviceProfile } from '../models/deviceProfile';

class RedisReceiver {
    constructor(app) {
        this.app = app;
        this.log = app.log.getLogger('redisTaskRevicer');
    }

    onMessage(channel, message) {
        this.log.info('redis onMessage info:', channel, message);
        if (!channel || !(channel in this)) {
            this.log.error('[redis_onMessage] not found match channel: %s', channel);
            return;
        }
        this[channel].call(this, message);
    }

    kmHb(deviceId) {
        const mysqlm = this.app.mysql;
        const log = this.log;

        co(function* gen() {
            const profile = yield DeviceProfile.findOneAndUpdate(
                { deviceId }, { 'state.km': 'close' }).exec();

            const info = {
                memo: profile.sys,
                wid: profile.wid,
            };

            try {
                const sql = `
                    select 
                        s.memo 
                    from sys_config s where s.sys = ?;
                `;

                let result = yield mysqlm.execute(sql, [info.memo]);
                result = result || [];
                info.memo = result[0].memo;
            } catch (e) {
                console.log(`[redisTaskRevicer] mysql error: ${e.message}`);
            }
            log.error(`[KHL_APP_ERR] km 心跳停止, ${info.memo}_${info.wid}: ${deviceId}`);
        });
    }
}

export default RedisReceiver;
